package Image;

import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.util.Hashtable;
import javax.media.jai.IHSColorSpace;
import javax.media.jai.JAI;

/**
 * Some static methods for working with Images see the methods for more info
 *
 * @author Seth Wessitsh <seth@wessitsh.com>
 */
public class ImageUtils {
	/**
	 * Creates a BufferedImage which uses the IHS ColorSpace
	 *
	 * @param imgToConvert an image with a ColorSpace other than IHS
	 *                     (i.e., wasted computations if already using IHS)
	 * @return a BufferedImage using the IHS ColorSpace
	 */
	public static BufferedImage getIHSImage(BufferedImage imgToConvert) {
		IHSColorSpace ihs = IHSColorSpace.getInstance();
		ColorModel IHSColorModel = new ComponentColorModel(
			ihs,
			new int[]{8, 8, 8},
			false, false,
			Transparency.OPAQUE,
			DataBuffer.TYPE_BYTE
		);
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(imgToConvert);
		pb.add(IHSColorModel);
		RenderedImage imageIHS = JAI.create("colorconvert", pb);

		return getBufferedImage(imageIHS);
	}

	/**
	 * Creates a BufferedImage from a RenderedImage
	 * 
	 * @param img the RenderedImage to create a BufferedImage from
	 * @return a BufferedImage representing img
	 */
	public static BufferedImage getBufferedImage(RenderedImage img) {
		if (img instanceof BufferedImage) return (BufferedImage)img;

		ColorModel cm = img.getColorModel();
		WritableRaster raster = cm.createCompatibleWritableRaster(
			img.getWidth(), img.getHeight()
		);

		Hashtable properties = new Hashtable();
		for (String key : img.getPropertyNames()) {
			properties.put(key, img.getProperty(key));
		}

		BufferedImage result = new BufferedImage(
			cm, raster, cm.isAlphaPremultiplied(), properties
		);
		img.copyData(raster);
		return result;
	}

}
